package com.shanghaionstar.home;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.weight.CustomImageView;
import com.shanghaionstar.R;
import com.shanghaionstar.enumtype.DealerBrandType;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.utils.Utilities;

/**
 * Created by kai zhang on 2016/1/26.
 */
public class HomeMrOLayout extends RelativeLayout {
    private Context mContext;
    private CustomImageView mroView;
    public int width, height;
    Rect outRect = new Rect();
    int[] location = new int[2];
    private boolean mDragging;
    private int mRegistrationX, mRegistrationY;
    private int mStatusBarHeight;
    private final int duration = 300;
    private int fixY;
    private boolean isLongClick = false;

    public HomeMrOLayout(Context context) {
        this(context, null);
    }

    public HomeMrOLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public HomeMrOLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        init();
    }

    private void init() {
        width = mContext.getResources().getDisplayMetrics().widthPixels;
        height = mContext.getResources().getDisplayMetrics().heightPixels;
        mroView = new CustomImageView(mContext);
        LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mroView.setLayoutParams(layoutParams);
        fixY = (int) (height / 5 - 68 * mContext.getResources().getDisplayMetrics().density);
        mroView.setTranslationY(fixY);
        refreshMroFigure();
//        mroView.setImageResource(mro_right);
        mStatusBarHeight = Utilities.getStatusBarHeight(mContext);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
//        LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
//        addView(mroView,layoutParams);
        addView(mroView);
        //手动触发一下动画，移动小O头像到右边
//        moveToRight(width / 2 + 180);
//        mroView.setTranslationX(getWidth() / 2 + 180);
//        moveToSide();
    }

    private boolean inViewInBounds(View view, int x, int y) {
        view.getDrawingRect(outRect);
        view.getLocationOnScreen(location);
        outRect.offset(location[0], location[1]);
        return outRect.contains(x, y);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        int mMotionDownX = (int) ev.getX();
        int mMotionDownY = (int) ev.getY();
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (inViewInBounds(mroView, mMotionDownX, mMotionDownY)) {
                    mDragging = true;
                    mroView.setImageResource(mro_front);
                } else {
                    mDragging = false;
                }
                break;
            case MotionEvent.ACTION_UP:
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_CANCEL:
                break;
        }
        return mDragging;
    }

    int mMotionDownX = 0;
    int mMotionDownY = 0;

    int distanceX = 0;
    int distanceY = 0;
    private boolean moving = false;
    private int lastMotionX = 0;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int mMotionDownX = (int) event.getX();
        int mMotionDownY = (int) event.getY();
        mMotionDownY += mStatusBarHeight;
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                moving = false;
                lastMotionX = mMotionDownX;
                getParent().requestDisallowInterceptTouchEvent(true);
                mRegistrationX = mMotionDownX - (location[0]);
                mRegistrationY = mMotionDownY + mStatusBarHeight - (location[1]);
                move(mMotionDownX, mMotionDownY);
                break;
            case MotionEvent.ACTION_UP:
                if (!moving) {
                    mroView.performClick();
                }
                move(mMotionDownX, mMotionDownY);
                moveToSide();
                mDragging = false;

                moving = false;
                break;
            case MotionEvent.ACTION_MOVE:
                final int deltaX = lastMotionX - mMotionDownX;
                boolean xMoved = Math.abs(deltaX) > new ViewConfiguration().getScaledEdgeSlop()-4;
                if (!moving && !xMoved) {
                    break;
                }
                moving = true;
                move(mMotionDownX, mMotionDownY);
                break;
            case MotionEvent.ACTION_CANCEL:
                mDragging = false;
                break;
        }
        return mDragging;
    }

    OnClickListener mListener;

    @Override
    public void setOnClickListener(OnClickListener l) {
        isLongClick = false;
        mListener = l;
        mroView.setOnClickListener(mListener);
    }

    @Override
    public void setOnLongClickListener(OnLongClickListener l) {
//        super.setOnLongClickListener(l);
        isLongClick = true;
    }

    private void moveToRight(int transX) {
        Drawable d = getResources().getDrawable(mro_right);
        if (d == null) return;
        int end = width - d.getIntrinsicWidth();
        ObjectAnimator oa = ObjectAnimator.ofFloat(mroView, "translationX", transX, end);
        oa.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mroView.setImageResource(mro_right);
            }
        });
        oa.start();
        int transY = (int) mroView.getTranslationY();
        if (transY != fixY) {
            ObjectAnimator.ofFloat(mroView, "translationY", transY, fixY).setDuration(duration).start();
        }
    }

    private void moveToSide() {
        LogManager.getInstance().d("mroView.getWidth():" + mroView.getWidth());
        LogManager.getInstance().d("getWidth():" + getWidth());
        int transX = (int) mroView.getTranslationX();
        if (transX >= 0) {
            float end = 0;
            if (transX + mroView.getWidth() / 2 > getWidth() / 2) {
                Drawable d = getResources().getDrawable(mro_right);
                if (d == null) return;
                int w = d.getIntrinsicWidth();
                end = getWidth() - w;
//                		mroView.getWidth();

            }
            final int _transX = transX;
            ObjectAnimator oa = ObjectAnimator.ofFloat(mroView, "translationX", transX, end);
            oa.setDuration(duration);
            oa.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    if (_transX + mroView.getWidth() / 2 > getWidth() / 2) {
                        mroView.setImageResource(mro_right);
                    } else {
                        mroView.setImageResource(mro_left);
                    }
                }
            });
            oa.start();
        }
//        int transY = (int) mroView.getTranslationY();
//        if (transY != fixY) {
//            ObjectAnimator.ofFloat(mroView, "translationY", transY, fixY).setDuration(duration).start();
//        }
    }

    private void move(int touchX, int touchY) {
        int transX = touchX - mRegistrationX;
        if (transX >= 0 && transX + mroView.getWidth() <= getWidth()) {
            mroView.setTranslationX(transX);
        }
        int transY = touchY - mRegistrationY;
        if (transY >= 0 && transY + mroView.getHeight() <= getHeight()) {
            mroView.setTranslationY(transY);
        }
    }

    public void showMro(boolean isShow) {
        if (isShow) {
            mroView.setVisibility(View.VISIBLE);
            if (mListener != null)
                mroView.setOnClickListener(mListener);
        } else {
            mroView.setOnClickListener(null);
            mroView.setVisibility(View.GONE);
        }
    }


    private DealerBrandType dealerBrandType;
    private int mro_front;
    private int mro_left;
    private int mro_right;

    private final int[] mro_buick = new int[]{R.drawable.mro_buick_left, R.drawable.mro_buick_front, R.drawable.mro_buick_right};
    private final int[] mro_cadilac = new int[]{R.drawable.mro_cadilac_left, R.drawable.mro_cadilac_front, R.drawable.mro_cadilac_right};
    private final int[] mro_chevlot = new int[]{R.drawable.mro_chevlot_left, R.drawable.mro_chevlot_front, R.drawable.mro_chevlot_right};
    private final int[] mro_wtk = new int[]{R.drawable.mro_wtk_left, R.drawable.mro_wtk_front, R.drawable.mro_wtk_right};
    private final int[] mro_default = new int[]{R.drawable.mro_default_left, R.drawable.mro_default_front, R.drawable.mro_default_right};

    public void refreshMroFigure() {
        dealerBrandType = getCurrentDealerBrandType();
        loadMroImages(dealerBrandType);
        int _transX = (int) mroView.getTranslationX();
        if (_transX + mroView.getWidth() / 2 > getWidth() / 2) {
            mroView.setImageResource(mro_right);
        } else {
            mroView.setImageResource(mro_left);
        }
        moveToSide();
    }

    private DealerBrandType getCurrentDealerBrandType() {
        String currentFigure = PreferencesUtls.getInstance(getContext()).getString(FinalConstants.MroConstants.MRO_FIGURE_KEY);
        if ("".equals(currentFigure) || FinalConstants.MroConstants.MRO_FIGURE_DEFAULT.equals(currentFigure)) {
            return DealerBrandType.DEFAULT;
        } else if (FinalConstants.MroConstants.MRO_FIGURE_BRAND.equals(currentFigure)) {
            return DealerBrandType.getDealerBrandTypeByDesc(ApplicationUtil.getInstance().getCarInfo());
        } else if (FinalConstants.MroConstants.MRO_FIGURE_WTK.equals(currentFigure)) {
            return DealerBrandType.WTK;
        } else {
            return DealerBrandType.DEFAULT;
        }
    }

    private void loadMroImages(DealerBrandType dealerBrandType) {
        switch (dealerBrandType) {
            case DEFAULT:
                mro_left = mro_default[0];
                mro_front = mro_default[1];
                mro_right = mro_default[2];
                break;
            case BUICK:
                mro_left = mro_buick[0];
                mro_front = mro_buick[1];
                mro_right = mro_buick[2];
                break;
            case CADILLAC:
                mro_left = mro_cadilac[0];
                mro_front = mro_cadilac[1];
                mro_right = mro_cadilac[2];
                break;
            case CHEVROLET:
                mro_left = mro_chevlot[0];
                mro_front = mro_chevlot[1];
                mro_right = mro_chevlot[2];
                break;
            case WTK:
                mro_left = mro_wtk[0];
                mro_front = mro_wtk[1];
                mro_right = mro_wtk[2];
                break;
            default:
                mro_left = mro_default[0];
                mro_front = mro_default[1];
                mro_right = mro_default[2];
        }
    }
}
